/*
 * @Author: your name
 * @Date: 2021-02-26 17:15:34
 * @LastEditTime: 2021-02-27 12:13:04
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \xgwsp_frontendd:\project\tsx\demo-tsx\src\axios\request\cancel.ts
 */
import axios, { AxiosRequestConfig, Canceler } from 'axios';

const w = window as any;
w._pendingMap = new Map<string, Canceler>();
export const pendingUrl = (config: AxiosRequestConfig) => [config.method, config.url].join('&');

export class AxiosCanceler {
  /**
   * @description: 添加请求
   */
  add(config: AxiosRequestConfig) {
    this.delete(config);
    const url = pendingUrl(config);
    config.cancelToken =
      config.cancelToken ||
      new axios.CancelToken((cancel) => {
        w._pendingMap.set(url, cancel);
      });
  }

  delete(config: AxiosRequestConfig) {
    const url = pendingUrl(config);
    if (w._pendingMap.has(url)) {
      const cancel = w._pendingMap.get(url);
      cancel && cancel('取消请求');
      w._pendingMap.delete(url);
    }
  }

  allDelete() {
    (window as any)._pendingMap.forEach((cancel: any) => {
      cancel && cancel();
      (window as any)._pendingMap.clear();
    });
  }
}
